<?php
namespace app\common\model\divide;
use think\Model;
use app\common\model\Setting as SettingModel;
use think\Db;
use think\Session;
class Service extends Model
{

    protected $name='divide_service';


    public static function getTypelist(){
        return [1=>'品牌商', 2=> '城市运营商', 3 => '城市合伙人'];
    }

    public static function getStatuslist(){
        return [0 =>'待分账', 1=> '已分账', 2 => '分账失败'];
    }
    public function wxapp(){
        return $this->belongsTo("app\common\model\Wxapp",'wxapp_id','wxapp_id');
    }
    /**
     * 从缓存中获取商城名称
     * @param $data
     * @return array
     */
    public function getStoreName($data)
    {
        $names = [];
        foreach ($data as $wxapp) {
            $names[$wxapp['wxapp_id']] = SettingModel::getItem('store', $wxapp['wxapp_id'])['name'];
        }
        return $names;
    }

    /**
     * 获取订单列表
     * @param array $query
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getList($query = []){
        // 设置查询条件
        !empty($query) && $this->setQueryWhere($query);
        // 获取列表数据
        return $this->with(['wxapp'])
            ->alias('service')
            ->field('service.*')
            ->join('wxapp', 'wxapp.wxapp_id = service.wxapp_id')
            ->order(['service.create_time' => 'desc'])
            ->paginate(15, false, [
                'query' => request()->request()
            ]);
    }
    /*
     * 获取字符串查询条件
     */
    private function getSelectStr($array,$field,$count){
        $str='';
        foreach($array as $k=>$v){
            if($k<$count-1){
                $str.=$v[$field].',';
            }else{
                $str.=$v[$field];
            }
        }
        return $str;
    }
    //获取所有下级id  (不包含类型)
    private function get_all_child($array,$id){
        $arr = array();
        foreach($array as $v){
            if($v['recommend_id']==$id){
                $arr[] = $v['agent_user_id'];
                $arr = array_merge($arr,$this->get_all_child($array,$v['agent_user_id']));
            }
        };
        return $arr;
    }


    /*
     * 获取当前登录代理的所有下级代理分红数据
     */
    public function getRivideList($query=[]){
        $storeStr=$this->getwxappNext();
        //设置查询条件
        !empty($query) && $this->setQueryWhere($query);
        //获取列表数据
        return $this->with(['wxapp'])
            ->alias('service')
            ->field('service.*')
            ->where('service.agent_id','in',$storeStr['agent'])
            ->where('wxapp.wxapp_id','in',$storeStr['wxapp'])
            ->join('wxapp', 'wxapp.wxapp_id = service.wxapp_id')
            ->order(['service.create_time' => 'desc'])
            ->paginate(15, false, [
                'query' => request()->request()
            ]);
    }
    /*
     * 获取当前登录代理所有下级代理商收入
     */
    public function getMoneyList($query=[]){
        $storeStr=$this->getwxappNext();
        //设置查询条件
        !empty($query) && $this->setQueryIncomeWhere($query);
        //获取列表数据
        return $this->where('agent_id','in',$storeStr['agent'])
            ->where('wxapp_id','in',$storeStr['wxapp'])
            ->field("name,type,FROM_UNIXTIME(create_time,'%Y-%m-%d') as dates,sum(abonus) as abonu,sum(amount) as amounts ,sum(payment) as payments")
            ->order(['dates' => 'desc','agent_id'=>'asc'])
            ->group("FROM_UNIXTIME(create_time,'%Y-%m-%d'),agent_id")
            ->paginate(15, false, [
                'query' => request()->request()
            ]);
    }
    private function getwxappNext(){
        //获取当前登录人所有下级代理
        $session = Session::get('yoshop_agent');
        if($session['agent']['type']==0){
            $agent_id = $session['agent']['agent_id'];
            $info=Db::name('agent_user')->where(['pinpai_id'=>$session['agent']['pinpai_id']])->select();
            $resNext=$this->get_all_child($info->toArray(),$agent_id);
            $resNext[]=$session['agent']['agent_id'];
        }else{
            $info=Db::name('agent_user')->where(['recommend_id'=>$session['agent']['agent_id']])->select();
            $resNext=[];
            if($info){
                foreach ($info as $k=>$v){
                    $resNext[]=$v['agent_user_id'];
                }
            }
            $resNext[]=$session['agent']['agent_id'];
        }
        $storeList=Db::name('wxapp')->where(['agent_id'=>['in',$resNext],'active'=>1])->field('wxapp_id')->select();
        $countWxapp=count($storeList);
        $array['wxapp']=$this->getSelectStr($storeList,'wxapp_id',$countWxapp);
        $array['agent']=$resNext;
        return $array;

    }

    /**
     * 设置查询条件
     * @param $query
     */
    private function setQueryWhere($query){
        // 设置默认的检索数据
        $params = $this->setQueryDefaultValue($query, [
            'status' =>-1,
            'type' =>-1,
        ]);

        //商户名称
        //!empty($params['search']) && $this->where('name', 'like', "%{$params['search']}%");
        if (isset($query['search']) && !empty($query['search'])) {
            $this->where('service.name|wxapp.wxapp_name', 'like', '%' . trim($query['search']) . '%');
        }
        // 充值方式
        $params['type'] > -1 && $this->where('service.type', '=', (int)$params['type']);
        // 支付状态
        $params['status'] > -1 && $this->where('service.status', '=', (int)$params['status']);
        // 起始时间
        !empty($params['start_time']) && $this->where('service.create_time', '>=', strtotime($params['start_time']));
        // 截止时间
        !empty($params['end_time']) && $this->where('service.create_time', '<', strtotime($params['end_time']) + 86400);

        if (isset($query['search_time']) && !empty($query['search_time'])) {
            $times=explode('至',$query['search_time']);
            $this->where('service.create_time','between time',$times);
        }
    }
    /**
     * 设置默认的检索数据
     * @param $query
     * @param array $default
     * @return array
     */
    protected function setQueryDefaultValue(&$query, $default = [])
    {
        $data = array_merge($default, $query);
        foreach ($query as $key => $val) {
            if (empty($val) && isset($default[$key])) {
                $data[$key] = $default[$key];
            }
        }
        return $data;
    }

    public function getIncomeList($query = []){
        // 设置查询条件
        !empty($query) && $this->setQueryIncomeWhere($query);

        // 获取列表数据
        return $this->field("name,type,FROM_UNIXTIME(create_time,'%Y-%m-%d') as dates,sum(abonus) as abonu,sum(amount) as amounts ,sum(payment) as payments")
            ->order(['dates' => 'desc','agent_id'=>'asc'])
            ->group("FROM_UNIXTIME(create_time,'%Y-%m-%d'),agent_id")
            ->paginate(15, false, [
                'query' => request()->request()
            ]);
    }

    private function setQueryIncomeWhere($query)
    {
        // 设置默认的检索数据
        $params = $this->setQueryDefaultValue($query, [
            'status' => '-1',
        ]);

        // 用户昵称/订单号
        if (isset($query['search']) && !empty($query['search'])) {
            $this->where('name', 'like', '%' . trim($query['search']) . '%');
        }
        // 起始时间
        !empty($params['start_time']) && $this->where('store.create_time', '>=', strtotime($params['start_time']));
        // 截止时间
        !empty($params['end_time']) && $this->where('store.create_time', '<', strtotime($params['end_time']) + 86400);

        if (isset($query['search_time']) && !empty($query['search_time'])) {
            $times=explode('至',$query['search_time']);
            $this->where('create_time','between time',$times);
        }
    }


    public function  getGather($query = []){
        // 设置查询条件
        !empty($query) && $this->setQueryIncomeWhere($query);

        // 获取列表数据
        return $this->field("name,type,FROM_UNIXTIME(create_time,'%Y-%m') as dates,sum(abonus) as abonu,sum(amount) as amounts ,sum(payment) as payments")
            ->order(['dates' => 'desc','agent_id'=>'asc'])
            ->group("FROM_UNIXTIME(create_time,'%Y-%m'),agent_id")
            ->paginate(15, false, [
                'query' => request()->request()
            ]);
    }
}